import store from '@/store/index'
/**
 *
 * 授权过后自动登录
 */
export const autoLogin = function() {
	return new Promise((resolve, reject) => {
		getCodeLogin((code) => {
			wxGetUserInfo().then(userInfo => {
				userInfo.code = code;
				return resolve(userInfo);
			}).catch(res => {
				return reject(res);
			})
		});
	})
}

/**
 * 获取用户信息
 */
export const wxGetUserInfo = function() {
	return new Promise((resolve, reject) => {
		uni.getUserInfo({
			lang: 'zh_CN',
			success(res) {
				resolve(res);
			},
			fail(res) {
				reject(res);
			}
		})
	});
}

/**
 * 获取code
 * @param {Object} successFn
 */
export const getCodeLogin = function(successFn) {
	uni.login({
		success(res) {
			successFn(res.code);
		}
	})
}

/**
 * 校驗是否登录状态
 */
export const checkLogin = function() {
	return !!uni.getStorageSync('token');
};

/**
 * 校驗微信是否登录状态
 */
export const checkWxLogin = function() {
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success: (res) => {
				if (!res.authSetting['scope.userInfo']) {
					return reject({
						authSetting: false
					});
				} else {
					// uni.getStorage({
					//     key: 'cache_key',
					//     success: (res) => {
					if (checkLogin()) {
						return resolve({
							userInfo: store.getters.userInfo,
							isLogin: true
						});
					} else {
						getCodeLogin((code) => {
							wxGetUserInfo().then(userInfo => {
								userInfo.code = code;
								return resolve({
									userInfo: userInfo,
									isLogin: false
								});
							}).catch(res => {
								return reject(res);
							})
						});
						// wxGetUserInfo().then(userInfo => {
						//     userInfo.code = res.data;
						//     return resolve({userInfo: userInfo, isLogin: false});
						// }).catch(res => {
						//     return reject(res);
						// })
					}
					//     },
					//     fail() {
					//         getCodeLogin((code) => {
					//             wxGetUserInfo().then(userInfo => {
					//                 userInfo.code = code;
					//                 return resolve({userInfo: userInfo, isLogin: false});
					//             }).catch(res => {
					//                 return reject(res);
					//             })
					//         });
					//     }
					// })

				}
			},
			fail(res) {
				return reject(res);
			}
		})
	})
}

//减法函数，用来得到精确的减法结果
//说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
//调用：$h.Sub(arg1,arg2)
//返回值：arg1减去arg2的精确结果
export const sub = function() {
	arg1 = parseFloat(arg1);
	arg2 = parseFloat(arg2);
	var r1, r2, m, n;
	try {
		r1 = arg1.toString().split(".")[1].length
	} catch (e) {
		r1 = 0
	}
	try {
		r2 = arg2.toString().split(".")[1].length
	} catch (e) {
		r2 = 0
	}
	m = Math.pow(10, Math.max(r1, r2));
	//动态控制精度长度
	n = (r1 >= r2) ? r1 : r2;
	return ((mul(arg1, m) - mul(arg2, m)) / m).toFixed(n);
}

//乘法函数，用来得到精确的乘法结果
//说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
//调用：$h.Mul(arg1,arg2)
//返回值：arg1乘以arg2的精确结果
export const mul = function() {
	arg1 = parseFloat(arg1);
	arg2 = parseFloat(arg2);
	var m = 0,
		s1 = arg1.toString(),
		s2 = arg2.toString();
	try {
		m += s1.split(".")[1].length
	} catch (e) {}
	try {
		m += s2.split(".")[1].length
	} catch (e) {}
	return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}


/**
 * Parse the time to string
 * @param {Object} time
 * @param {Object} cFormat
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}
